#define _SVID_SOURCE  1
#include "../include/structure.h"

int main(int argc, char* argv[]){
	// 初始化进程池
	proc_status_t list[3];
	initPool(list, 3);

	// 监听socket
	int socket_fd;
	initSocket(&socket_fd, "192.168.169.128", "8080");

	int epoll_fd = epoll_create(1);
	addEpoll(epoll_fd, socket_fd);

	for(int i = 0; i < 3 ; i++){
		addEpoll(epoll_fd, list[i].local_socket_fd);
	}

	while(1){
		struct epoll_event events[5];
		int epoll_num = epoll_wait(epoll_fd, events, 5, -1);

		for(int i = 0; i < epoll_num; i++){
			struct epoll_event ev = events[i];

			if(ev.data.fd == socket_fd){
				// 有新连接到来
				int net_fd = accept(socket_fd, NULL, NULL);

				// 把net_fd交给子进程
				toSon(net_fd, list, 3);
				// TODO: 交给池中进程

				close(net_fd);

			}else{
				// 子进程发消息，把子进程由busy变free
				char buf[60];
				int ret = recv(events->data.fd, buf, sizeof buf, 0);
				ERROR_CHECK(ret, -1, "recv");
				// 发送的内容无关紧要，只是通知父进程让子进程变成free状态
				//printf("buf = %s\n", buf);

				for(int k = 0; k < 3; k++){
					if(list[k].local_socket_fd == ev.data.fd){
                        list[k].status = FREE;
                        break;
                    }
				}
			}
		}
		

	}
	close(socket_fd);

	return 0;
}